package com.llw.notify.util;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import java.text.MessageFormat;

/**
 * 帮助构造 Toast 的类，包含两种使用方法：
 *      - 使用静态方法：该方法需要每次传入 Context，打印日志
 *      - 使用实例：包含两种构造方式
 *          - 仅传入 Context 构造，不会打印日志
 *          - 传入 Context 和 TAG 构造，显示 Toast 的同时打印日志
 */
public class ToastLogger {
    // 内部日志标签
    private static final String INNER_LOG_TAG = ToastLogger.class.getSimpleName();
    // 外部调用者的日志标签
    private final String OUTER_LOG_TAG;
    // 输出外部日志时的日志信息前缀
    private final String OUTER_LOG_PREFIX = "<" + ToastLogger.class.getSimpleName() + " log>: ";
    // 实例化 ToastMaker 使用的Context
    private final Context CONTEXT;

    public ToastLogger(final Context context, final String tag) {
        this.CONTEXT = context;
        this.OUTER_LOG_TAG = tag;
        Log.i(INNER_LOG_TAG, this.toString());
    }

    public ToastLogger(final Context context) {
        this.CONTEXT = context;
        this.OUTER_LOG_TAG = null;
        Log.i(INNER_LOG_TAG, this.toString());
    }

    @NonNull
    @Override
    public String toString() {
        final String activity = Utils.getActivityNameByContext(this.CONTEXT);
        return MessageFormat.format("<{0}> '{' Activity: {1}, Outer Tag: {2} '}'",
                ToastLogger.class.getSimpleName(),
                activity != null ? activity : "Unknown",
                this.OUTER_LOG_TAG != null ? this.OUTER_LOG_TAG : "null");
    }

    private static void base(final Context context, final String message, final int length) {
        Log.i(ToastLogger.INNER_LOG_TAG, message);
        Toast.makeText(context, message, length).show();
    }

    public static void s(final Context context, final String message) {
        base(context, message, Toast.LENGTH_SHORT);
    }

    public static void l(final Context context, final String message) {
        base(context, message, Toast.LENGTH_LONG);
    }

    private void base(final String message, final int length) {
        if (this.OUTER_LOG_TAG != null) {
            Log.i(this.OUTER_LOG_TAG, this.OUTER_LOG_PREFIX + message);
        }
        Toast.makeText(this.CONTEXT, message, length).show();
    }

    public void s(final String message) {
        base(message, Toast.LENGTH_SHORT);
    }

    public void l(final String message) {
        base(message, Toast.LENGTH_LONG);
    }
}
